package com.roc.web.action.terminal;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.roc.newPage.IPageService;
import com.roc.page.BaseSearchCondition;
import com.roc.page.PaginationBaseAction;
import com.roc.pojo.Estidinfo;
import com.roc.pojo.Operators;
import com.roc.pojo.TblInsInf;
import com.roc.service.IorgService;
import com.roc.service.ServiceException;
import com.roc.service.operator.IPowerInfoService;
import com.roc.util.Constance;
import com.roc.util.constant.ConfigMerinfoUtil;
import com.roc.util.constant.ConfigProperties;
import com.roc.util.constant.Constant;
import com.roc.util.constant.Role;
import com.roc.util.constant.TerminalFlag;

@Controller
@Scope(BeanDefinition.SCOPE_PROTOTYPE)
@Namespace("/ysbTermSnReplace")
public class YsbTermSnReplaceQueryAction extends PaginationBaseAction {

	private static final long serialVersionUID = 1L;
	
	private Logger logger=LogManager.getLogger(YsbTermSnReplaceQueryAction.class);
	
	private YsbTermSnReplaceQuerySearchCondition searchCondition;
	private List<TblInsInf> orgList;	
	@Autowired
	IorgService orgService;
	@Autowired
	IPageService pagenitionService;
	
	@Autowired
	IPowerInfoService powerInfoService;
	
	/**
	 * 初始化终端换机申请页面（云商宝）
	 * @return
	 * @throws Exception
	 */
	@Action(value = "init", results = { @Result(name = "success", location = "/pages/terminal/ysbTermSnReplaceList.jsp"),@Result(name = "error", location = "/error.jsp")
    })
	public String queryTerminalJspAction() throws Exception{
		Operators op = (Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
		Map<String, String> map=powerInfoService.queryRealIdByOpId(op.getSuperiorId(), op.getRoleType(), op.getId(), op.getOrgCode());
        String superRole= map.get("superRole");
		if( !op.getRoleType().equals( Role.SYSTEM.getCode() )  
				&& !( op.getRoleType().equals( Role.OPERATORS_COMM.getCode() ) && superRole.equals( Role.SYSTEM.getCode() ) ) ) {
			addActionError("当前登录账号无权限访问!!!");
			return ERROR;
		}
		org();
		return SUCCESS;
	}
	/**
	 * 终端换机申请页面查询（云商宝）
	 * @return
	 * @throws Exception
	 */
	@Action(value = "queryYsbTermSnReplaceList", results = { @Result(name = "success", location = "/pages/terminal/ysbTermSnReplaceList.jsp"),
			@Result(name = "error", location = "/error.jsp")
           })
	//查询终端
	public String queryYsbTermSnReplaceList() throws Exception{
		Operators op = (Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
		Map<String, String> map=powerInfoService.queryRealIdByOpId(op.getSuperiorId(), op.getRoleType(), op.getId(), op.getOrgCode());
        String superRole= map.get("superRole");
		if( !op.getRoleType().equals( Role.SYSTEM.getCode() )  
				&& !( op.getRoleType().equals( Role.OPERATORS_COMM.getCode() ) && superRole.equals( Role.SYSTEM.getCode() ) ) ) {
			addActionError("当前登录账号无权限访问!!!");
			return ERROR;
		}
		try {			
			
			if(searchCondition==null){
				searchCondition=(YsbTermSnReplaceQuerySearchCondition)getSearchConditionFromSession();
			if(searchCondition==null){
				searchCondition=new YsbTermSnReplaceQuerySearchCondition();
				}
			}
			org();			
			int rows=pagenitionService.countSQL(searchCondition);
			if(rows>0){
				searchRsList=pagenitionService.findAllSQL(searchCondition, calcuStart(getCurrentPage()), Constance.PAGE_MAX_SIZE);
			}
			dealWithTheListSpecially(searchRsList);	
			this.setTotalPage(this.calcuTotalPage(rows));
			getRequest().setAttribute(SEARCH_RS_LIST, searchRsList);
			getRequest().setAttribute(CURRENT_PAGE, this.getCurrentPage());
			getRequest().setAttribute(TOTAOL_PAGE, this.getTotalPage());
			setSearchToConditionSession(searchCondition);			
		} catch (ServiceException e) {			
			logger.error(e.getMessage(),e);
			addActionError(e.getMessage());
			return ERROR;
			
		}			
		return SUCCESS;
	}
	

	@Override
	protected void dealWithTheListSpecially(List<Object> list) {
		List<Estidinfo> estidList= new ArrayList<Estidinfo>();
		if(list!=null&&list.size()>0){
			Iterator<Object> iterator=list.iterator();
			while (iterator.hasNext()) {
				Object[] obj= (Object[])iterator.next();
				Estidinfo est=new Estidinfo(); 
				for(TblInsInf bean:orgList){
					if(Constance.Null2EmptyTrim(obj[0]).equals(bean.getInsIdCd())){
						est.setOrgCode(bean.getInsName());
					}
				}
				est.setMid(Constance.Null2EmptyTrim(obj[1]));
				est.setMidName(Constance.Null2EmptyTrim(obj[2]));
				est.setTidName(Constance.Null2EmptyTrim(obj[3]));
				est.setTerTid(Constance.Null2EmptyTrim(obj[4]));
				est.setTidKind(ConfigMerinfoUtil.getPosType(Constance.Null2EmptyTrim(obj[5])));
				est.setFlagName(TerminalFlag.valueOfCode(Constance.Null2EmptyTrim(obj[6])).getName());
				est.setFlag(Constance.Null2EmptyTrim(obj[6]));
				est.setSerialNum(Constance.Null2EmptyTrim(obj[7]));

				String brandCode = obj[8] + "";
				String nameCode = obj[9] + "";
				
				est.setPosBrand(ConfigMerinfoUtil.getPosBRAND(brandCode));
				est.setPosName(ConfigMerinfoUtil.getPosMODEL(nameCode , brandCode));
				estidList.add(est);
			}
			list.clear();
			list.addAll(estidList);
		}
	}
	//查询机构
	public void org() throws Exception{	    
		orgList=orgService.queryOrgList();				
		getRequest().setAttribute("orgList", orgList);	
		getRequest().setAttribute("brandMap",ConfigProperties.getYsbBrandProperties());
		getRequest().setAttribute("nameMap", new ArrayList<Map<String,Object>>());			
	}
	
	@Override
	protected BaseSearchCondition getSearchConditionFromSubClass()
			throws Exception {
		
		return searchCondition;
	}

	@Override
	protected void setSearchConditionToSubClass(
			BaseSearchCondition searchCondition) throws Exception {		
		this.setSearchConditionToSubClass(searchCondition);
	}

	@Override
	protected void setSearchToConditionSession(
			BaseSearchCondition searchCondition) {
		getSession().setAttribute(SEARCH_SESSION_YSB_TERM_SN_REPLACE, searchCondition);		
	}

	@Override
	protected BaseSearchCondition getSearchConditionFromSession() {
		
		return (YsbTermSnReplaceQuerySearchCondition)getSession().getAttribute(SEARCH_SESSION_YSB_TERM_SN_REPLACE);
	}

	@Override
	protected String getInitPageSize() {		
		return Constance.PAGE_MAX_SIZE+"";
	}

	public YsbTermSnReplaceQuerySearchCondition getSearchCondition() {
		return searchCondition;
	}

	public void setSearchCondition(
			YsbTermSnReplaceQuerySearchCondition searchCondition) {
		this.searchCondition = searchCondition;
	}

}
